package ioc05;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Author：汤小洋
 * Date：2023-08-10 17:10
 * Description：IoC容器持有者，用于获取IoC容器中的bean
 */
public class ApplicationContextHolder implements ApplicationContextAware{

    private static ApplicationContext ac;

    /**
     * 会自动注入当前的IoC容器
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ac = applicationContext;
    }

    /**
     * 根据名称获取bean
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName){
        return ac.getBean(beanName);
    }

    /**
     * 根据类型获取bean
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T getBean(Class<T> clazz){
        return ac.getBean(clazz);
    }

}
